package models

import (
	"comment/util"
	"strconv"
	"time"

	"github.com/astaxie/beego/orm"
)

type Comment struct {
	ID           int       `orm:"column(id);pk;auto" json:"id" form:"-"`
	Phone        string    `orm:"column(phone)" json:"phone"`
	Content      string    `orm:"column(content)" json:"content"`
	Object       string    `orm:"column(object)" json:"object"`
	Subject      string    `orm:"column(subject)" json:"subject"`
	CommentTime  string    `orm:"column(comment_time)" json:"commentTime"`
	ArticleTitle string    `orm:"column(article_title)" json:"articleTitle"`
	ArticleUrl   string    `orm:"column(article_url)" json:"articleUrl"`
	User         *User     `orm:"rel(fk);null" json:"auditor"`
	AuditTime    string    `orm:"column(audit_time)" json:"auditTime"`
	AuditState   string    `orm:"column(audit_state)" json:"auditState"`
	AuditOpinion string    `orm:"column(audit_opinion)" json:"auditOpinion"`
	HotReview    string    `orm:"column(hot_review)" json:"hotReview"`
	HotTime      string    `orm:"column(hot_time)" json:"hotTime"`
	CreateDate   time.Time `orm:"auto_now_add;type(datetime)" json:"-"`
}

func init() {
	orm.RegisterModel(new(Comment))
}

func GetCommentByID(id int) (interface{}, error) {
	var (
		obj Comment
		err error
	)
	o := orm.NewOrm()
	qs := o.QueryTable(new(Comment)).Filter("id", id)
	if err = qs.RelatedSel().One(&obj); err == nil {
		return obj, nil
	}
	return nil, err
}

func CommentAudit(state string, ids []string, opinion string, id int) error {
	var (
		err       error
		auditTime string
	)
	if state != "0" {
		auditTime = time.Now().Format("2006-01-02 15:04:05")
	}
	o := orm.NewOrm()
	p, _ := o.Raw("update `comment` set audit_state = ?, audit_opinion = ?, audit_time = ?, user_id = ? where id =?").Prepare()
	for i := 0; i < len(ids); i++ {
		_, err = p.Exec(state, opinion, auditTime, id, ids[i])
	}
	p.Close()
	switch state {
	case "0":
		saveLog(ids, id, "执行了待审核操作")
	case "1":
		saveLog(ids, id, "执行了审核通过操作")
	case "2":
		saveLog(ids, id, "执行了审核拒绝操作")
	}
	return err
}

func CommentHot(hot string, ids []string, id int) error {
	var (
		err     error
		hotTime string
	)

	if hot == "1" {
		hotTime = time.Now().Format("2006-01-02 15:04:05")
	}
	o := orm.NewOrm()
	p, _ := o.Raw("update `comment` set hot_review = ?, hot_time = ? where id =?").Prepare()
	for i := 0; i < len(ids); i++ {
		_, err = p.Exec(hot, hotTime, ids[i])
	}
	p.Close()
	switch hot {
	case "0":
		saveLog(ids, id, "执行了取消热评操作")
	case "1":
		saveLog(ids, id, "执行了推荐热评操作")
	}
	return err
}

func CommentList(pageNo int, pageSize int, m map[string]interface{}) (interface{}, error) {
	orm.Debug = true
	var (
		objArrs []Comment
		count   int64
		err     error
	)
	o := orm.NewOrm()
	qs := o.QueryTable(new(Comment))
	cond := orm.NewCondition()
	for k, v := range m {
		cond = cond.And(k, v)
	}
	qs = qs.SetCond(cond)
	if count, err = qs.Count(); err == nil {
		if _, err = qs.Limit(pageSize, (pageNo-1)*pageSize).RelatedSel("user").OrderBy("-hot_time", "-comment_time").All(&objArrs); err == nil {
			total, _ := strconv.Atoi(strconv.FormatInt(count, 10))
			return util.PageUtil(total, pageNo, pageSize, objArrs), nil
		}
	}
	return nil, err
}

func saveLog(ids []string, userId int, content string) error {
	var obj Comment
	o := orm.NewOrm()
	p, _ := o.Raw("insert into `log` (user_id, module, content, create_date)values(?, ?, ?, ?)").Prepare()
	for i := 0; i < len(ids); i++ {
		o.QueryTable(new(Comment)).Filter("id", ids[i]).One(&obj)
		phone := obj.Phone
		_, err := p.Exec(userId, "评论管理", phone+content, time.Now().Format("2006-01-02 15:04:05"))
		return err
	}
	p.Close()
	return nil
}

func SaveComment(comment *Comment) (int64, error) {
	o := orm.NewOrm()
	id, err := o.Insert(comment)
	return id, err
}
